<script setup lang='ts'>
import type { FormItemRule } from 'element-plus'

import { useAddOrUpdateConfig, useChangeConfigEnable, useGetConfigItemList } from '@fl/api/man-api'
import { SearchTable } from '@fl/components'
import ButtonItem from '@fl/components/button-item.vue'
import { cloneDeep } from 'lodash-es'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

import { btns, formState, initPage } from './constant'

const router = useRouter()

const showDiglog = ref(false)
const tableData = ref<any>([])

// 新增类目表单
const tablePage = ref<any>(cloneDeep(initPage))

const form = ref<any>(cloneDeep(formState))

const gridOptions = reactive<any>({
    columns: [
        { fixed: 'left', title: '序号', type: 'seq', width: 50 },
        { field: 'itemName', title: '配置名称' },
        { slots: { default: 'status' }, title: '启用状态' },
        { slots: { default: 'operate' }, title: '操作', width: 250 },
    ],
    rowConfig: {
        keyField: 'id',
    },
    toolbarConfig: {
        slots: {
            buttons: 'toolbar_buttons',
        },
    },
})

const params = computed(() => ({
    pageNum: tablePage.value.currentPage,
    pageSize: tablePage.value.pageSize,
}))

const { data, isLoading, refetch } = useGetConfigItemList(params)

const formCol: any = [
    {
        fieldProps: {
            maxlength: 20,
        },
        label: '配置名称',
        prop: 'itemName',
    },
    {
        fieldProps: {
            maxlength: 300,
        },
        label: '配置值',
        prop: 'itemValue',
    },
    {
        label: '是否启用多配置项',
        options: [
            {
                label: '是',
                value: 1,
            },
            {
                label: '否',
                value: 0,
            },
        ],
        prop: 'multipleChoice',
        valueType: 'radio',
    },
    {
        label: '启用状态',
        prop: 'isEnabled',
        valueType: 'switch',
    },
]

function validateName(_rule: FormItemRule, value: string, callback: Fn): void {
    const pattern = /\s/
    if (!value) {
        callback(new Error('请输入配置名称'))
    }
    if (pattern.test(value))
        callback(new Error('配置名称不允许输入空格'))

    else
        callback()
}
function validateValue(_rule: FormItemRule, value: string, callback: Fn): void {
    const pattern = /\s/
    if (!value) {
        callback(new Error('请输入配置值'))
    }
    if (pattern.test(value))
        callback(new Error('请输入配置值不允许输入空格'))

    else
        callback()
}
const rules = {
    itemName: [{ required: true, trigger: 'blur', validator: validateName }],
    itemValue: [{ required: true, trigger: 'blur', validator: validateValue }],
}

function doAction(item: any, row: any) {
    switch (item.value) {
        case 'list':
            view(row)
            break
        case 'edit':
            const obj = {
                ...row,
                isEnabled: row.isEnabled === 0,
            }
            form.value = cloneDeep(obj)
            showDiglog.value = true
            break

        default:
            break
    }
}

function doAdd() {
    form.value = cloneDeep(formState)
    showDiglog.value = true
}

const { mutate: addOrUpdateMutate } = useAddOrUpdateConfig()

const { mutate: changeStatusMutate } = useChangeConfigEnable()
function doSave() {
    const params = {
        ...form.value,
        isEnabled: form.value.isEnabled ? 0 : -1,
    }
    addOrUpdateMutate(params, {
        onSuccess: () => {
            ElMessage.success('操作成功')
            showDiglog.value = false
            refetch()
        },
    })
}

function changeStatus(row: any) {
    console.log(row)
    const params = {
        id: row.id,
        isEnabled: row.isEnabled === 0 ? -1 : 0,
    }
    changeStatusMutate(params, {
        onSuccess: () => {
            ElMessage.success('操作成功')
        },
    })
}
function view(row: any) {
    router.push({
        path: '/operations-pages/system-setting/system-configuration-info',
        query: {
            parentId: row.id,
        },
    })
}

watchEffect(() => {
    if (data.value) {
        tableData.value = cloneDeep(data.value?.rows) ?? []
        tablePage.value.total = data.value.total ?? 0
    }
})
</script>

<template>
    <ElCard shadow="never">
        <SearchTable v-bind="gridOptions"
                     v-model:pager="tablePage"
                     v-loading="isLoading"
                     :data="tableData"
                     :seq-config="{ startIndex: (tablePage.currentPage - 1) * tablePage.pageSize }"
        >
            <template #toolbar_buttons>
                <ElButton type="primary"
                          @click="doAdd"
                >
                    新增
                </ElButton>
            </template>

            <template #status="{ row }">
                <vxe-switch :model-value="row.isEnabled === 0"
                            @change="changeStatus(row)"
                />
            </template>

            <template #dictType="{ row }">
                <span class="c-#337ab7 cursor-pointer"
                      @click="view(row)"
                >{{ row.dictType }}</span>
            </template>

            <template #operate="{ row }">
                <ButtonItem :btns="btns"
                            @btn-click="doAction($event, row)"
                />
            </template>
        </SearchTable>
    </ElCard>

    <PlusDialogForm v-model:visible="showDiglog"
                    v-model="form"
                    :title="form?.dictId ? '编辑' : '新增'"
                    :form="{ columns: formCol, rules, labelWidth: 150, labelPosition: 'top' }"
                    @confirm="doSave"
    />
</template>

<style lang="scss" scoped>
</style>
